import 'package:bruno/bruno.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';

import '../../AppConfig/CityLIstData.dart';
import '../../AppConfig/Config.dart';
import '../../http/NoLoadingGetApi.dart';
import '../../l10n/messages.dart';

class chooseCitySheet extends StatefulWidget {
  const chooseCitySheet({super.key, required this.chooseType, required this.cityData, required this.chooseCityList, required this.chooseCodeList});
  final int chooseType;
  final List cityData;
  final List chooseCityList;
  final List chooseCodeList;
  @override
  State<chooseCitySheet> createState() => _chooseCitySheetState();
}

class _chooseCitySheetState extends State<chooseCitySheet> {

  String selectedProvince = '';
  String selectedCity = '';
  String selectedDistrict = '';
  String selectedProvinceCode = '';
  String selectedCityCode = '';
  String selectedDistrictCode = '';
  // List cityData = [];

  String storedData = '';
  int selectedTileIndexone=-1;
  int selectedTileIndextwo=-1;
  int selectedTileIndexthree=-1;
  List checkCityList=[];
  List checkCityCodeList=[];
  String searchTerm = "";
  String proviceStr="";
  FocusNode focusNode = FocusNode();
  BrnSearchTextController scontroller = BrnSearchTextController();
  TextEditingController textController = TextEditingController();
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    ///initState 中添加监听，记得销毁
    textController.addListener(() {
      if (focusNode.hasFocus) {
        if (!BrunoTools.isEmpty(textController.text)) {
          scontroller.isClearShow = true;
          scontroller.isActionShow = true;
        }
      }
    });
    focusNode.addListener(() {
      if (focusNode.hasFocus) {
        if (!BrunoTools.isEmpty(textController.text)) {
          scontroller.isClearShow = true;
        }
      }
    });
    // if(widget.chooseCityList.isNotEmpty){
    //   selectedProvince=widget.chooseCityList[0];
    //   selectedCity=widget.chooseCityList[1];
    //   selectedDistrictCode=widget.chooseCityList[2];
    //   selectedProvinceCode = widget.chooseCodeList[0];
    //   selectedCityCode = widget.chooseCodeList[1];
    //   selectedDistrictCode = widget.chooseCodeList[2];
    //
    //
    // }
  }
  List<String> findAllDistricts(Map<String, dynamic> city) {
    List<String> allDistricts = [];

    void collectDistricts(Map<String, dynamic> node) {
      if (node.containsKey('children') && node['children'] is List<dynamic>) {
        List<dynamic> children = node['children'];
        for (var child in children) {
          if (child is Map<String, dynamic>) {
            allDistricts.add(child['cityName']);
            collectDistricts(child);
          }
        }
      }
    }

    collectDistricts(city);
    return allDistricts;
  }

  List<String> findAllDistrictCodes(Map<String, dynamic> city) {
    List<String> allDistrictCodes = [];

    void collectDistrictCodes(Map<String, dynamic> node) {
      if (node.containsKey('children') && node['children'] is List<dynamic>) {
        List<dynamic> children = node['children'];
        for (var child in children) {
          if (child is Map<String, dynamic>) {
            allDistrictCodes.add(child['postalCode']);
            collectDistrictCodes(child);
          }
        }
      }
    }

    collectDistrictCodes(city);
    return allDistrictCodes;
  }

  Map<String, dynamic>? findCityAndPostalCode(List<dynamic> cities, String searchTerm) {
    for (var city in cities) {
      try {
        var cityMap = city as Map<String, dynamic>;
        if (cityMap['cityName'] == searchTerm) {
          return cityMap;
        } else if (cityMap['children'] != null && cityMap['children'] is List<dynamic>) {
          var result = findCityAndPostalCode(cityMap['children'], searchTerm);
          if (result != null) {
            return result;
          }
        }
      } catch (e) {
        // Handle type conversion exception
      }
    }
    return null;
  }
  String findProvinceByPostalCode(List<dynamic> cities, String postalCode) {
    Map<String, dynamic>? city = findCityByPostalCode(cities, postalCode);

    if (city != null) {
      // 如果找到的城市就是省份，直接返回
      if (city['level'] == '1') {
        return city['cityName'] ?? '';
      }

      String provinceName = findTopLevelParentProvince(cities, city);
      return provinceName;
    }

    return '';
  }

  String findTopLevelParentProvince(List<dynamic> cities, Map<String, dynamic> city) {
    String parentId = city['parentCity'] ?? '';

    // 递归查找省份
    if (parentId.isNotEmpty) {
      Map<String, dynamic>? parentCity = findCityById(cities, parentId);

      if (parentCity != null) {
        if (parentCity['level'] == '1') {
          return parentCity['cityName'] ?? '';
        } else {
          return findTopLevelParentProvince(cities, parentCity);
        }
      }
    }

    return '';
  }

  Map<String, dynamic>? findCityByPostalCode(List<dynamic> cities, String postalCode) {
    return cities.firstWhere(
          (city) => city is Map<String, dynamic> && city['postalCode'] == postalCode,
      orElse: () => null,
    );
  }

  Map<String, dynamic>? findCityById(List<dynamic> cities, String cityId) {
    return cities.firstWhere(
          (city) => city is Map<String, dynamic> && city['parentCity'] == cityId,
      orElse: () => null,
    );
  }
//重置后2位
  String resetLastTwoDigits(String postalCode) {
    if (postalCode.length >= 2) {
      return postalCode.substring(0, postalCode.length - 2) + '00';
    }
    return postalCode;
  }
//重置后3位
  String resetLastThreeDigits(String postalCode) {
    if (postalCode.length >= 3) {
      return postalCode.substring(0, postalCode.length - 3) + '000';
    }
    return postalCode;
  }
  @override
  Widget build(BuildContext context) {
    final screenSize = MediaQuery.of(context).size;
    var messages = AppLocalizations.of(context)!;
    return Container(
      decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.all(Radius.circular(10))),
      height: 500.h,
      child: Column(
        children: [
          SizedBox(height: 10.h,),
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              TextButton(onPressed: (){Navigator.pop(context);}, child:  Text("     取消     ",style: TextStyle(color: Colors.black,fontSize: 14.sp),),),

              Text(widget.chooseType==1||widget.chooseType==2 ?"选择装货地":widget.chooseType==4?"请选择收货地":"选择卸货地",style: TextStyle(color: Colors.black,fontSize: 16.sp,fontWeight: FontWeight.w600),),
              TextButton(onPressed: (){  if(selectedProvince==""){
                BrnToast.show("请选择省", context);
              }else if(selectedCity==""){
                BrnToast.show("请选择市", context);
              }else if(selectedDistrict==""){
                BrnToast.show("请选择区", context);
              }else{
                Navigator.pop(context, [selectedProvince,selectedCity,selectedDistrict,selectedProvinceCode,selectedCityCode,selectedDistrictCode]);
              }}, child:   Text("     确认     ",style: TextStyle(color:MyColors.themeColor,fontSize: 14.sp),),),



            ],
          ),
          Container(
            height: 40.h,
            decoration: BoxDecoration(
              borderRadius: BorderRadius.all(Radius.circular(10)),
            ),
            child: GestureDetector(
              onTap: () {
                FocusScope.of(context).requestFocus(focusNode);
              },
              child: AbsorbPointer(
                absorbing: true,
                child: BrnSearchText(
                  focusNode: focusNode,
                  controller: textController,
                  searchController: scontroller..isActionShow = false,
                  innerColor:MyColors.backgreyColor,
                  borderRadius:BorderRadius.all(const Radius.circular(10.0)),
                  hintText:"搜索城市名称",
                  onTextClear: () {
                    debugPrint('sss');
                    setState(() {
                      checkCityList=[];
                      checkCityCodeList=[];
                    });
                    return false;
                  },
                  autoFocus: false, // 设置为false，不自动获取焦点
                  onActionTap: () {
                    scontroller.isClearShow = false;
                    scontroller.isActionShow = false;
                    focusNode.unfocus();
                    // BrnToast.show('取消', context);
                    setState(() {});
                  },
                  onTextCommit: (text) {
                    BrnToast.show('提交内容 : $text', context);
                  },
                  onTextChange: (text) {
                    NoLoadinggetApiManager.getData(
                      context, // 上下文对象，用于显示提示信息等
                      'api/system/dev/cityDict/geyByKey', // 您的API端点
                      {"key":text}, // 查询参数，如果没有可以传递null
                          (responseData)  {
                        setState(() {

                          for (var item in responseData['data']) {
                            checkCityList.add(item["fullName"]);
                            checkCityCodeList.add(item["postalCode"]);
                          }
                        });
                      },
                    );
                    // List<dynamic> cityData = MyCityListData.CityList;
                    // searchTerm = text;
                    // Map<String, dynamic>? city = findCityAndPostalCode(cityData, searchTerm);
                    // String province = findProvinceByPostalCode(cityData, selectedProvinceCode);
                    // print('$searchTerm 所在的省份是 $province');
                    //
                    // if (city != null) {
                    //   List<String> allDistricts = findAllDistricts(city);
                    //   List<String> allDistrictCodes = findAllDistrictCodes(city);
                    //
                    //   if (allDistricts.isNotEmpty) {
                    //     print("All Districts: ${allDistricts.join(', ')}");
                    //     setState(() {
                    //       checkCityList=allDistricts;
                    //       searchTerm = text;
                    //       if (province!="") proviceStr =province;
                    //     });
                    //   } else {
                    //     print("No districts found");
                    //   }
                    //
                    //   if (allDistrictCodes.isNotEmpty) {
                    //     print("All District Codes: ${allDistrictCodes.join(', ')}");
                    //
                    //     setState(() {
                    //       checkCityCodeList =allDistrictCodes;
                    //       searchTerm = text;
                    //     });
                    //   } else {
                    //     print("No district codes found");
                    //   }
                    // } else {
                    //   print("City not found");
                    // }
                    // BrnToast.show('输入内容 : $text', context);
                  },
                ),
              ),
            ),
          ),
          SizedBox(height: 10.h,),
          !checkCityList.isEmpty&&checkCityList.length<27?
          Container(
            height: 240.h,
            color: Colors.white,
            padding: EdgeInsets.only(top: 8.h),
            child: ListView.builder(
                itemCount: checkCityList.length,
                itemBuilder: (BuildContext context, int index) {
                  return Container(
                    padding: EdgeInsets.only(left: 8.w,right: 8.w),
                    child: Column(
                      children: [
                        GestureDetector(
                          child:Row(
                            mainAxisAlignment: MainAxisAlignment.spaceBetween,
                            children: [
                              Row(
                                children: [
                                  Text(searchTerm+" "+checkCityList[index],style: TextStyle(color:Colors.black,fontSize: 14.sp),),
                                ],
                              ),

                            ],
                          ),
                          onTap: (){
                            setState(() {
                              List<String> parts = checkCityList[index].split('-');
                              int tag = checkCityList[index].indexOf('-');
                              int count = parts.length - 1; // 分隔后的列表长度减去1就是 '-' 的个数
                              if (count == 2) {
                                selectedProvince = parts[0];
                                selectedCity = parts[1];
                                selectedDistrict = parts[2];
                                selectedProvinceCode=checkCityCodeList[index].substring(0, 2)+"0000";
                                selectedCityCode=checkCityCodeList[index].substring(0, 4)+"00";
                                selectedDistrictCode=checkCityCodeList[index];
                              } else if (count == 1) {
                                selectedProvince = parts[0];
                                selectedCity = parts[1];
                              } else {
                                selectedProvince = checkCityList[index];
                              }
                              // selectedCity=searchTerm;
                              // selectedDistrict= checkCityList[index];
                              // selectedCityCode=resetLastTwoDigits(checkCityCodeList[index]);
                              // selectedProvinceCode=resetLastThreeDigits(checkCityCodeList[index]);
                              // selectedDistrictCode=checkCityCodeList[index];
                              // selectedProvince=findProvinceByPostalCode(MyCityListData.CityList, selectedProvinceCode);
                              // print("pcode:$selectedProvince,citycode:$selectedCity,concode:$selectedDistrict");
                              // print("pcode:$selectedProvinceCode,citycode:$selectedCityCode,concode:$selectedDistrictCode");
                            });
                            Navigator.pop(context, [selectedProvince,selectedCity,selectedDistrict,selectedProvinceCode,selectedCityCode,selectedDistrictCode]);
                          },
                        ),

                        Divider(height: 16.h,color: MyColors.backgreyColor,),
                      ],
                    ),
                  );
                }
            ),

          )
              :Container(
            width: screenSize.width,
            height: 380.h,
            child:   Row(
              children: [

                // 显示省份列表
                Expanded(
                  child:   Container(
                    color: MyColors.backgreyColor,
                    child:   buildListViewOne(MyCityListData.CityList, (item) {
                      setState(() {
                        selectedProvince = item['cityName'];
                        selectedProvinceCode = item['postalCode'];
                        selectedCity = '';
                        selectedDistrict = '';
                        print(selectedProvinceCode);
                      });
                    }),
                  ),

                ),
                // 显示城市列表
                Expanded(
                  child: buildListViewTwo(
                    findSelectedProvince()?.containsKey('children') ?? false
                        ? findSelectedProvince()!['children']
                        : [],
                        (item) {
                      setState(() {
                        selectedCity = item['cityName'];
                        selectedDistrict = '';
                        selectedCityCode = item['postalCode'];
                        print(selectedCityCode);
                      });
                    },
                  ),
                ),
                // 显示区域列表
                Expanded(
                  child: buildListViewThree(
                    findSelectedCity()?.containsKey('children') ?? false
                        ? findSelectedCity()!['children']
                        : [],
                        (item) {
                      setState(() {
                        selectedDistrict = item['cityName'];
                        selectedDistrictCode = item['postalCode'];
                        print(selectedDistrictCode);
                      });
                    },
                  ),
                ),
              ],
            ),
          ),

        ],
      ),
    );
  }


  Map<String, dynamic> findParentCity(List<dynamic> cities, String parentCityId) {
    return cities
        .whereType<Map<String, dynamic>>()
        .firstWhere((city) => city['citytName'] == parentCityId, orElse: () => {});
  }

  Map<String, dynamic>? findSelectedProvince() {
    return MyCityListData.CityList.firstWhere(
          (province) => province['cityName'] == selectedProvince,
      orElse: () => <String, dynamic>{},
    );
  }

  Map<String, dynamic>? findSelectedCity() {
    return findSelectedProvince()?['children']?.firstWhere(
          (city) => city['cityName'] == selectedCity,
      orElse: () => <String, dynamic>{},
    );
  }

  Widget buildListViewOne(List<dynamic> dataList, Function(Map<String, dynamic>) onTap) {
    return ListView.builder(
      itemCount: dataList.length,
      itemBuilder: (context, index) {
        return ListTile(
          title: Text(
            dataList[index]['cityName'],
            style: TextStyle(fontSize: 14.sp,
                color: index == selectedTileIndexone? MyColors.themeColor : Colors.black
            ),
          ),
          onTap: () {
            selectedTileIndexone = index;
            print(selectedTileIndexone);
            onTap(dataList[index]);
          },
        );
      },
    );
  }

  Widget buildListViewTwo(List<dynamic> dataList, Function(Map<String, dynamic>) onTap) {
    return ListView.builder(
      itemCount: dataList.length,
      itemBuilder: (context, index) {
        return ListTile(
          title: Text(
            dataList[index]['cityName'],
            style: TextStyle(fontSize: 14.sp,
              color: index == selectedTileIndextwo? MyColors.themeColor : Colors.black,
            ),
          ),
          onTap: () {
            selectedTileIndextwo = index;
            print(selectedTileIndextwo);
            onTap(dataList[index]);
          },
        );
      },
    );
  }

  Widget buildListViewThree(List<dynamic> dataList, Function(Map<String, dynamic>) onTap) {
    return ListView.builder(
      itemCount: dataList.length,
      itemBuilder: (context, index) {
        return ListTile(
          title: Text(
            dataList[index]['cityName'],
            style: TextStyle(fontSize: 14.sp,
              color: index == selectedTileIndexthree? MyColors.themeColor : Colors.black,
            ),
          ),
          onTap: () {
            selectedTileIndexthree = index;
            print(selectedTileIndexthree);
            onTap(dataList[index]);
          },
        );
      },
    );
  }
}